<template>
    <div>
        <BasicTable @register="registerTable" class="ov">
            <template #toolbar>
                <div>
                    <Space class="flex justify-end">
                        <a-button type="primary" @click="handleShowChart">查看图形分析</a-button> 
                        <a-button type="primary" @click="handleDayExport" :loading="dayExportLoading">充电日报表导出</a-button> 
                        <a-button type="primary" @click="handleExport" :loading="exportLoading">停车统计报表导出</a-button> 
                        <Popconfirm title="确认要求重新计算并设置未支付么?" @confirm="handleRecomputed">
                            <a-button type="primary" danger :loading="recomputedLoading">强制重新计算并设置未支付</a-button> 
                        </Popconfirm>

                    </Space>
                    <!-- <Space>
                        <div>充电总量（度）:{{ summaryData.power }}</div>
                        <div>电费（元）:{{ summaryData.powerMoney }}</div>
                        <div>服务费（元）:{{ summaryData.serviceMoney }}</div>
                        <div>停车费（元）:{{ summaryData.parkMoney }}</div>
                        <div>超时占桩费（元）:{{ summaryData.pileTimeoutSumFee }}</div>
                        <div>总金额（元）:{{ summaryData.spendMoney }}</div>
                        <div>优惠金额（元）:{{ summaryData.benefitAmount }}</div>
                        <div>实付（元）:{{ summaryData.actualAmount }}</div>
                    </Space> -->
                </div>
                    
            </template>
        </BasicTable>
        <MonthChart @register="registerModal"></MonthChart>
    </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    name: 'ChargeOrder',
});
</script>
<script lang="ts" setup>
import { ref, onMounted, h } from 'vue';
import { BasicTable, useTable, TableAction, BasicColumn } from '@/components/Table';
import { Space, Popconfirm } from 'ant-design-vue';
import { defHttp } from '@/utils/http/axios';
import { useMessage } from '@/hooks/web/useMessage';
import dayjs from 'dayjs';
import _ from 'lodash';
import { downloadBlob } from '@/utils/file/download';
import { isNotNull } from '@/utils/objUtil.ts'
import { useModal } from '@/components/Modal';
import MonthChart from './monthChart.vue';

import qs from 'qs';
const { createMessage } = useMessage();
const orderStatusList = ref([])
const payStatusList = ref([])
const getStatus = async () => {
    orderStatusList.value = await defHttp.get({ url: '/admin/main/orderStatusList' });
    payStatusList.value = await defHttp.get({ url: '/admin/main/paymentStatusList' });
}
onMounted(async() => {
    await getStatus()
})
const payDetail = (id) => {}
const payDetail2 = (id) => {}

const exportLoading = ref(false);
const dayExportLoading = ref(false);
const sumData = ref(0)
const columns: BasicColumn[] = [
    {
        title: 'ID',
        dataIndex: 'id',
        width: 80,
        fixed: 'left',
    },
    {
        title: '订单编号',
        dataIndex:'sn',
        width: 300,
    },
    {
        title: '订单状态',
        dataIndex: 'orderStatus',
        width: 120,
        customRender: ({ record }) => {
            return orderStatusList.value.find(item => item.value.toString() === record.orderStatus)?.label || '';
        },
    },
    {
        title: '支付方式',
        dataIndex: 'payMethodId',
        width: 120,
        customRender: ({ record }) => {
            if (record.payMethodId === 2) {
                return h('a', {'onclick': payDetail(record.id), style: 'color: #0a8ddf'}, '微信支付')
            } else if (record.payMethodId === 4) {
                return '余额支付'
            } else if (record.payMethodId === 5) {
                return h('a', {'onclick': payDetail2(record.id), style: 'color: #0a8ddf'}, '微信委托扣款')
            }
            return '-'
        },
    },
    {
        title: '支付状态',
        dataIndex: 'payStatus',
        width: 120,
        customRender: ({ record }) => {
            const { payMethodId, entrustStatus } = record
            let extra = ''
            if (payMethodId === 5) {
                if (entrustStatus === 0) {
                    extra = '(未发起)'
                } else if (entrustStatus === 1) {
                    extra = '(扣款中)'
                } else if (entrustStatus === 2) {
                    extra = '(委托扣款成功)'
                } else if (entrustStatus === 3) {
                    extra = '(扣款失败)'
                }
            }
            return payStatusList.value.find(item => item.value.toString() === record.payStatus)?.label  + extra;        
        },
    },
    {
        title: '姓名',
        dataIndex: 'memberName',
        width: 120,
    },
    {
        title: '手机号',
        dataIndex: 'mobile',
        width: 120,
        customRender: ({ record }) => {
            const { mobile } = record
            return mobile ? mobile : '-'
        },
    },
    {
        title: '用户性质',
        dataIndex: 'userNature',
        width: 120,
        customRender: ({ record }) => {
            const { companyName } = record
            return companyName ? companyName : '平台用户'
        },
    },
    {
        title: '充电站',
        dataIndex:'stationName',
        width: 180,
    },
    {
        title: '充电终端',
        dataIndex: 'pileName',
        width: 120,
    },
    {
        title: '开始时间',
        dataIndex:'startTime',
        width: 160,
        customRender: ({ record }) => {
            return record.startDate == null ? '': dayjs(record.startDate).format('YYYY-MM-DD HH:mm:ss');
        },
    },
    {
        title: '结束时间',
        dataIndex: 'endTime',
        width: 160,
        customRender: ({ record }) => {
            return record.endDate == null ? '': dayjs(record.endDate).format('YYYY-MM-DD HH:mm:ss');
        },
    },
    {
        title: '充电时长(分)',
        dataIndex: 'chargeTime',
        width: 120,
    },
    {
        title: '充电总量(度)',
        dataIndex: 'power',
        width: 120, 
    },
    {
        title: '电费(元)',
        dataIndex: 'powerMoney',
        width: 120,
    },
    {
        title: '服务费(元)',
        dataIndex: 'serviceMoney',
        width: 120,
    },
    {
        title: '停车费(元)',
        dataIndex: 'parkMoney',
        width: 120,
    },
    {
        title: '超时占桩费(元)',
        dataIndex: 'pileTimeoutSumFee',
        width: 120,
    },
    {
        title: '总金额(元)',
        dataIndex: 'spendMoney',
        width: 120,
    },
    {
        title: '优惠金额(元)',
        dataIndex: 'benefitAmount',
        width: 120,
    },
    {
        title: '实付(元)',
        dataIndex: 'actualAmount',
        width: 120,
        customRender: ({ record }) => {
            const { payStatus } = record
            if (payStatus === 0) {
                return '-'
            } else if (payStatus === 1) {
                return record.actualAmount;
            }
        }
    },
    {
        title: '启动方式',
        dataIndex:'startUpTerminal',
        width: 120,
        customRender: ({ record }) => {
            if (record.startUpTerminal === 0) {
                return 'APP'
            } else if (record.startUpTerminal === 1) {
                return '小程序'
            } else if (record.startUpTerminal === 2) {
                return 'VIN'
            }
            return ''
        },
    },
    {
        title: '停止原因',
        dataIndex:'stopReason',
        width: 220,
    },
    {
        title: '车队名称',
        dataIndex: 'carTeamName',
        width: 120,
    },
    {
        title: '操作人员账号',
        dataIndex: 'companyAdminUserName',
        width: 120,
    },
    {
        title: '操作人员姓名',
        dataIndex: 'companyAdminName',
        width: 120,
    },
];
const searchFormSchema: FormSchema[] = [
    {
        component: 'ApiSelect',
        label: '电站',
        field: 'stationId',
        componentProps: ({ formModel }) => {
            return {
                api: '/admin/main/stationList',
                valueField: 'id',
                labelField: 'name',
                showSearch: true,
                allowClear: true,
                onChange: () => {
                    formModel.pileId = undefined;
                }
            }
        },
    },
    {
        component: 'ApiSelect',
        label: '电桩',
        field: 'pileId',
        componentProps: ({ formModel }) => {
            return {
                api: '/admin/main/pileList',
                params: {
                    stationId: formModel.stationId
                },
                valueField: 'id',
                labelField: 'name',
                showSearch: true,
                allowClear: true,
            }
        },
    },
    {
        component: 'ApiSelect',
        label: '企业',
        field: 'companyId',
        componentProps: {  
            api: '/admin/main/companyList',
            valueField: 'id',
            labelField: 'name',
            showSearch: true,
            allowClear: true,
        }
    },
    {
        component: 'ApiSelect',
        label: '订单状态',
        field: 'orderStatus',
        componentProps: {  
            api: '/admin/main/orderStatusList',
            allowClear: true,
        }
    },
    {
        component: 'ApiSelect',
        label: '支付状态',
        field: 'payStatus',
        componentProps: {  
            api: '/admin/main/paymentStatusList',
            allowClear: true,
        }
    },
    {
        component: 'Input',
        label: '单号',
        field: 'sn',
    },
    {
        component: 'RangePicker',
        label: '时间范围',
        field: '[startTime, endTime]',
        componentProps: {
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD',
        },
    },
    {
        component: 'Input',
        label: '姓名或手机号',
        field: 'name',
        componentProps: {
            allowClear: true,
        },
    },
    {
        component: 'Select',
        label: '启动方式',
        field: 'startUpTerminal',
        componentProps: {
            options: [
                {
                    label: '小程序',
                    value: '1',
                },
                {
                    label: 'VIN',
                    value: '2',
                },
            ],
        },
    },
    {
        component: 'Select',
        label: '支付方式',
        field: 'payMethodId',
        componentProps: {
            options: [
                {
                    label: '请选择',
                    value: '',
                },
                {
                    label: '微信支付',
                    value: '2',
                },
            ],
        },
    },
    {
        component: 'Input',
        label: '车队名称',
        field: 'carTeamName',
        componentProps: {
            allowClear: true,
        }
       }
]
// const summaryData = ref([])
const [registerTable, { getForm, getDataSource, reload, getSelectRowKeys }] =
useTable({
    api: '/admin/charge_order/list',
    useSearchForm: true,
    columns,
    showIndexColumn: true,
    indexColumnProps: {
        fixed: 'left',
    },
    rowKey: 'id',
    rowSelection: {
        type: 'checkbox',
    },
    formConfig: {
        labelWidth: 100,
        baseColProps: {
            span: 8,
        },
        schemas: searchFormSchema,
    },
    pagination: true,
    bordered: true,
    afterFetch: (data) => {
        // defHttp.get({ url: '/admin/charge_order/summary' }, { params: { ...getForm().getFieldsValue() } }).then((res) => {
        //     summaryData.value = res
        // })
    }
});
const handleDayExport = async() => {
    try {
        dayExportLoading.value = true;
        const formData = getForm().getFieldsValue()
        const ids = getSelectRowKeys();
        let exportData = {}
        if (ids && ids.length > 0) {
            exportData = {ids,importType: 'checkBox'}
            const res = await defHttp.get({ url: '/admin/charge_order/exportExcel?' + qs.stringify(exportData, { arrayFormat: 'repeat' }), responseType: 'blob' }, { isReturnNativeResponse: true });
            downloadBlob(res);
        } else {
            debugger
            exportData = { ...formData }
            if (isNotNull(formData)) {
                const res = await defHttp.get({ url: '/admin/charge_order/exportExcel', responseType: 'blob', params: { ...exportData } }, { isReturnNativeResponse: true });
                downloadBlob(res);
            } else {
                createMessage.error('请选择筛选条件');
            }
        }
    } finally {
        dayExportLoading.value = false;
    }
}		
const handleExport = async() => {
    try {
        exportLoading.value = true;
        const formData = getForm().getFieldsValue()
        
        const ids = getSelectRowKeys();
        let exportData = {}
        if (ids && ids.length > 0) {
            exportData = {ids, importType: 'checkBox'}
            
            const res = await defHttp.get({ url: '/admin/charge_order/exportParkExcel?' + qs.stringify(exportData, { arrayFormat: 'repeat' }), responseType: 'blob' }, { isReturnNativeResponse: true });
            downloadBlob(res);
        } else {
            exportData = { ...formData }
            if (isNotNull(formData)) {
                const res = await defHttp.get({ url: '/admin/charge_order/exportParkExcel', responseType: 'blob', params: { ...exportData } }, { isReturnNativeResponse: true });
                downloadBlob(res);
            } else {
                createMessage.error('请选择筛选条件');
            }
        }
    } finally {
        exportLoading.value = false;
    }
}

const handleRecomputed = () => {
    if (getSelectRowKeys().length !== 1) {
        createMessage.error('请选择单条数据');
        return;
    }
    const id = getSelectRowKeys()[0];
    defHttp.post({ url: `/admin/charge_order/reCalcOrderPay/${id}` }).then(() => {
        createMessage.success('操作成功');
        reload();
    })
}




const [registerModal, { openModal }] = useModal();
const handleShowChart = () => {
    openModal(true, {
        
    });
}
</script>
<style lang="less" scoped>
    // ::deep(.ov .vben-basic-table-header__toolbar) {
    //     display: block !important;
    // }
</style>
 